import { dispatch_statistc, tags,distributors,distributor_stores,sales_categories,distributor_area,staff_config,export_config,product_attribute_group} from '@/services/ant-design-pro/api';
import type { ProColumns } from '@ant-design/pro-components';
import FilterPanel from '@/components/FilterPanel';
import StatisticPanel from '@/components/statisticPanel';
import {
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { useEffect, useRef, useState } from 'react';
import { SearchOutlined } from '@ant-design/icons';
import { Input, Button, message,Progress,Modal } from 'antd';
import { history, useLocation } from 'umi';
import React from 'react';
import { saveAs } from 'file-saver';
import type { ActionType } from '@ant-design/pro-components';
import dayjs from 'dayjs';



const dispatch_detail: React.FC = () => {
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [dataTotal, setdataTotal] = useState<number>(0);
  const [dynamicColumns, setDynamicColumns] = useState<ProColumns<any>[]>([]);
  const [loading, setLoading] = useState(false);
  const [fields, setFields] = useState<any[]>([]);
  const [statistic, setStatistics] = useState<any[]>([]);
  const location = useLocation();
  const actionRef = useRef<ActionType>()
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  })
  const [exporting, setExporting] = useState(false); // 控制导出进度状态
  const [exportProgress, setExportProgress] = useState(0);
  // 顶部定义 ref
  const progressRef = useRef(0);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  
  const convertToCascaderOptions = (data: any[]): any[] => {
    return data.map(item => {
      const option: any = {
        value: item.id,
        label: item.name,
      };
  
      if (Array.isArray(item.children) && item.children.length > 0) {
        option.children = convertToCascaderOptions(item.children);
      }
  
      return option;
    });
  };

  // 初始化 URL 参数作为表单初始值
  const urlParams = new URLSearchParams(location.search);
  const initialValues: Record<string, any> = {};
  urlParams.forEach((value, key) => {
    if (key === 'bill_date') {
      // 将日期字符串按 , 拆分
      const [start, end] = value.split(',');
      if (start && end) {
        const startDate = dayjs(new Date(start)); // 将 GMT 字符串转为 Date，再转为 dayjs
        const endDate = dayjs(new Date(end));
        if (startDate.isValid() && endDate.isValid()) {
          initialValues.bill_date = [startDate, endDate];
        }
      }  
    } else if (key === 'area_lv') {
      const [lv1, lv2] = value.split(',');
      
      initialValues.area_lv_1 = lv1;
      initialValues.area_lv_2 = lv2;
      initialValues.area_lv = [lv1, lv2].filter(Boolean); // ✅ 用于 Cascader 初始化值
    }
    else if (key === 'group_by') {
      // 处理group_by参数，按逗号分割为数组
      initialValues.dimension = value.split(',').filter(Boolean);}
    else if (key === 'status') {
        // 处理group_by参数，按逗号分割为数组
        initialValues.status = value.split(',').filter(Boolean);}
    else {
      initialValues[key] = value;
    };
  });

  const exportCSV = async () => {{
    if (!dataSource || dataSource.length === 0) {
      message.warning('暂无数据可导出');
      return;
    }
    setExporting(true);
    setExportProgress(0);
  
    // 启动定时器模拟进度条
    const startSimulateProgress = () => {
      progressRef.current = 0;
      setExportProgress(0);
    
      timerRef.current = setInterval(() => {
        if (progressRef.current < 99) {
          progressRef.current += 1;
          setExportProgress(progressRef.current);
        } else {
          clearInterval(timerRef.current!);
        }
      }, 1000);
    };
    
    const stopSimulateProgress = () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
      setExportProgress(100);
    };
  
    try {
      // 显示遮罩和进度条
      startSimulateProgress();
      // 调接口获取全量数据，不影响当前页面表格状态
      const res_export = await  dispatch_statistc({
        _method:"export",
        status: initialValues?.status ?? "5,6,1",
        tag: initialValues?.tag ?? "",
        begin_billdate: initialValues?.bill_date?.[0]?.format('YYYY-MM-DD') ?? "",
        end_billdate: initialValues?.bill_date?.[1]?.format('YYYY-MM-DD') ?? "",
        receiver_id: initialValues?.distributor_id?? "",
        receiver_type: initialValues?.distributor_id? "4" : "",//如果选择的是distributor_id，receiver_type为4;
        origin_order_type: initialValues?.type?? "",
        area_lv_1: initialValues?.area_lv_1?? "",
        area_lv_2: initialValues?.area_lv_2?? "",
        turnover_store_id: initialValues?.turnover_store_id?? "",
        group_by: Array.isArray(initialValues?.dimension)? initialValues?.dimension.join(',') : "", // group_by: filterParams.dimension?.join(',') || "",
        page: "1",
        page_size: String(dataTotal),
      });
  
      const fullData = res_export?.data || [];
  
      if (fullData.length === 0) {
        message.warning('导出数据为空');
        return;
      }
  
      // 构建 CSV 内容
      const headers = Object.keys(fullData[0]).join(',') + '\n';
      const rows = fullData
        .map(row =>
          Object.values(row)
            .map(value => {
              const str = value === null || value === undefined ? '' : value.toString();
              return `"${str.replace(/"/g, '""')}"`;
            })
            .join(',')
        )
        .join('\n');
  
    const csvContent = headers + rows;
  
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const now = new Date();
    const formattedDate = now.toISOString().slice(0, 10); // 例如 2025-06-05
    saveAs(blob, `${formattedDate}_发货明细.csv`);
    // 请求完成时，调用 finish 停止进度条并跳到100%
    stopSimulateProgress();
    message.success('导出成功');
    } catch (error) { 
      console.log(error);
      message.error('导出失败，请重试');
    } finally {
      setTimeout(() => {
        setExporting(false);
        setExportProgress(0);
      }, 800); // 延迟关闭遮罩
    }}
  }

    const select = async () => {
      
      const res_tag = await tags({});
      const tagOptions = res_tag?.data?.map((item: any) => ({
        label: item,
        value: item,
      })) || [];

      const status= [
        { 
          "label": "待审核",
          "value": "2",
        },
        {  
        "label": "已通知配货",
        "value": "5",
      },
      {
        "label": "已通知出库",
        "value": "6",
      },
      {
        "label": "已完结",
        "value": "1",
      }];
      const res_distributors = await distributors({});
      const distributorsOptions = res_distributors ?.data?.map((item: any) => ({
        label: item.name,
        value: item.id,
      })) || [];
      
      const res_distributor_stores = await distributor_stores({});
      const distributor_storesOptions = res_distributor_stores ?.data?.map((item: any) => ({
        label: item.name,
        value: item.id,
      })) || [];

      const res_sales_categories = await sales_categories({});
      const sales_categoriesOptions = res_sales_categories ?.data?.map((item: any) => ({
        label: item,
        value: item,
      })) || [];

      const res_distributor_area = await distributor_area({});
      // 调用方法，转换为 Cascader 所需的格式
      const distributor_areaOptions = convertToCascaderOptions(res_distributor_area?.data || []);
        setFields([
          {
            label: '账期标签',
            name: 'tag',
            type: 'select',
            options: tagOptions,
            required: true,
          },
          {
            label: '单据日期',
            name: 'bill_date',
            type: 'rangePicker',
          },
          {
            label: '单据状态',
            name: 'status',
            type: 'select',
            options: status,
            fieldProps: {
              mode: 'multiple',  // ✅ 多选要放在 fieldProps 里
              allowClear: true,
              placeholder: '请选择单据状态',
            },
          },
    
          {
            label: '管理区域',
            name: 'area_lv',
            type: 'cascader',
            options: distributor_areaOptions,
            
            // required: true,
          },
          {
            label: '源单类型',
            name: 'type',
            type: 'select',
            options: sales_categoriesOptions,
            
            // required: true,
          },
          {
            label: '经销商名称',
            name: 'distributor_id',
            type: 'select',
            options: distributorsOptions,
            
            // required: true,
          },
          {
            label: '下级店铺',
            name: 'turnover_store_id',
            type: 'select',
            options: distributor_storesOptions,
            
            // required: true,
          }
        ]);
  };
  const statistic_dimension = async () => {
    // 调用basic的export_config
    const res_staff_config = await staff_config({});
    const dispatch_id = res_staff_config?.data?.setting?.invoiceReview?.id;
    // 若果没有需要saleID,按照默认维度

    //调用basic的product_attribute_group获取属性
    const res_product_attribute_group = await product_attribute_group({status:"1"}); 
    const product_attribute_groupOptions = res_product_attribute_group?.data?.map((item: any) => ({
      label: item.name,
      value: item.name,
    }))
   // 若果没有需要saleID,按照默认维度
    if(!dispatch_id){
      const dimensionOptions= [
        {  //如果saleId不存在，固定dimension选项
          "label": "单据编号",
          "value": "单据编号"
        },
        {  //如果saleId不存在，固定dimension选项
          "label": "单据日期",
          "value": "单据日期"
        },
        {  //如果saleId不存在，固定dimension选项
        "label": "客户名称",
        "value": "客户名称"
      },
      {
        "label": "款号",
        "value": "款号"
      },
      {
        "label": "品名",
        "value": "品名"
      },
      {
        "label": "颜色",
        "value": "颜色"
      },
      {  //如果saleId不存在，固定dimension选项
        "label": "色号",
        "value": "色号"
      },
      {  //如果saleId不存在，固定dimension选项
        "label": "尺码",
        "value": "尺码号"
      },...
       product_attribute_groupOptions   
      ]
      setStatistics([
        {
          label: '统计维度',
          name: 'dimension',
          type: 'select',
          options: dimensionOptions,
          fieldProps: {
            mode: 'multiple',  // ✅ 多选要放在 fieldProps 里
            allowClear: true,
            placeholder: '请选择统计维度',
          },
        },
      ]);    
    }
    else{
      const res_export_config = await export_config({ type: "4", mode: "stock_list" });
      const export_config_result = res_export_config?.data?.list?.find(
        (item: { id: string }) => item.id === dispatch_id
      );
      let export_configOptions: { label: string; value: string }[] = [];   
      if (export_config_result?.template_setting?.title) {
        const titleString = export_config_result.template_setting.title;
        const dataSettingString = export_config_result.template_setting.data_setting;
        const titleArray: string[] = titleString.split(',').map((title: string) => title.trim());
        const dataSettings: string[] = dataSettingString.split(',').map((item: string) => item.trim());
        const excludedFields = [
          "stock.cost_amount",
          "stock.tag_amount",
          "stock.quantity",
          "stock.dispatch_quantity",
          "stock.stockout_quantity",
          "product.attribute_units",
          "product.description",
        ];
         // 遍历 title 和 data_setting 的对应项，只保留未被排除的项
        const filteredTitles =titleArray.filter((_, index) => {
          const dataField = dataSettings[index];
          return !excludedFields.includes(dataField);
        });
        export_configOptions = filteredTitles.map(title => ({
          label: title,
          value: title,
        }));
      }
      const dimensionOptions= [
        ...export_configOptions,...
       product_attribute_groupOptions   
      ]
      setStatistics([
        {
          label: '统计维度',
          name: 'dimension',
          type: 'select',
          options: dimensionOptions,
          fieldProps: {
            mode: 'multiple',  // ✅ 多选要放在 fieldProps 里
            allowClear: true,
            placeholder: '请选择统计维度',
          },
        }, 
      ])   
    }}
  const loadData = async (filterParams?: any) => {
    if (!filterParams?.tag) {
      message.warning('请先选择账期');
      return;
    }

    setLoading(true);
    const [startDateRaw, endDateRaw] = filterParams.bill_date || [];
    const startDate = startDateRaw ? dayjs(startDateRaw) : null;
    const endDate = endDateRaw ? dayjs(endDateRaw) : null;

    const res = await dispatch_statistc({
      page_size: filterParams.pageSize || "", // 添加page_size参数
      page: filterParams.current || "", 
      status: Array.isArray(filterParams.status) && filterParams.status.length > 0 ? filterParams.status.join(',') : "5,6,1",
      tag: filterParams.tag || "",
      begin_billdate: startDate?startDate.format('YYYY-MM-DD') :"",
      end_billdate: endDate?endDate.format('YYYY-MM-DD') :"",
      receiver_id: filterParams.distributor_id || "",
      receiver_type: filterParams.distributor_id? "4" : "",//如果选择的是receiver_id，receiver_type为4;
      origin_order_type: filterParams.type || "",
      area_lv_1: filterParams.area_lv?.[0] || "",
      area_lv_2: filterParams.area_lv?.[1] || "",
      turnover_store_id: filterParams.turnover_store_id || "",
      group_by: Array.isArray(filterParams.dimension) ? filterParams.dimension.join(',') : "", // group_by: filterParams.dimension?.join(',') || "",
    });

    const data = res?.data || [];
    const total = res?.total || 0;
    setPagination({
      current: filterParams.current || 1,
      pageSize: filterParams.pageSize || 20,
      total,
    });

    setDataSource(data);
    setdataTotal(total);

    if (data.length > 0) {
      const firstItem = data[0];
      const columns: ProColumns<any>[] = Object.keys(firstItem).map((key) => ({
        title: key,
        dataIndex: key,
        ellipsis: false,
        copyable: false,
        search: false,
        align: 'left',
        filters: false,
        // sorter: true, //
        // onFilter: (value, record) => {
        //   return record[key]
        //     ?.toString()
        //     .toLowerCase()
        //     .includes((value as string).toLowerCase());
        // },
        // filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
        //   <div style={{ padding: 8 }}>
        //     <Input
        //       placeholder={`搜索 ${key}`}
        //       value={selectedKeys[0]}
        //       onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
        //       onPressEnter={() => confirm()}
        //       style={{ width: 188, marginBottom: 8, display: 'block' }}
        //     />
        //     <Button
        //       type="primary"
        //       onClick={() => confirm()}
        //       size="small"
        //       style={{ width: 90, marginRight: 8 }}
        //     >
        //       搜索
        //     </Button>
        //     <Button
        //       onClick={() => {
        //         clearFilters?.();
        //         confirm();
        //       }}
        //       size="small"
        //       style={{ width: 90 }}
        //     >
        //       重置
        //     </Button>
        //   </div>
        // ),
        // filterIcon: filtered => (
        //   <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />
        // ),
        onCell: () => ({
          style: {
            whiteSpace: 'nowrap',
            minWidth: '100px'
          }
        })
      }));
      setDynamicColumns(columns);
    }

    setLoading(false);
  };

  const handleSearch = (values: Record<string, any>) => {
    const params = new URLSearchParams();
    // 只在没有dimension参数时清空group_by（即FilterPanel触发时）
    if (!values.dimension) {
      params.delete('group_by');
    }

    // ✅ 安全拆解 area_lv
    if (Array.isArray(values.area_lv)) {
      const [lv1, lv2] = values.area_lv;
      if (lv1) {
        params.set('area_lv', lv2 ? `${lv1},${lv2}` : lv1);
      }
    }
    // 添加统计维度参数
    if (values.dimension) {
      params.set('group_by', values.dimension.join(','));
    }
    // 添加状态参数
    if (values.status) {
      params.set('status', values.status.join(','));
    }
  
    Object.entries(values).forEach(([key, value]) => {
      if (key === 'bill_date' && Array.isArray(value)) {
        const [start, end] = value;
        if (start && end) {
          params.set(key, `${dayjs(start).format('YYYY-MM-DD')},${dayjs(end).format('YYYY-MM-DD')}`);
        }
      }else if (value != null && key !== 'dimension') {
        params.set(key, value); 
      }
    });
  
    // 保留当前路径，只更新 search 参数
    history.replace({
      pathname: location.pathname, // 当前路径
      search: params.toString(),   // 更新的查询参数
    });
    loadData(values);
  };

  useEffect(() => {
    select();
    statistic_dimension();
    if (initialValues) {
      loadData(initialValues);
    };

  }, []);
  

  return (
    <PageContainer loading={loading} header={{
      title: false, // 👈 关闭标题显示
    }}>
  <Modal
    title="正在导出数据"
    visible={exporting}
    footer={null}
    closable={false}
    centered
    maskClosable={false}
  ><Progress percent={exportProgress} status="active" /></Modal>
      <FilterPanel fields={fields} onSearch={handleSearch} initialValues={initialValues} />
      <ProTable<any>
        headerTitle={
          <div style={{ display: 'flex', alignItems: 'center', height: 40,  paddingTop: 20, // ✅ 向下偏移
          }}>
             {dataSource.length > 0 && (
            <StatisticPanel
              fields={statistic}
              initialValues={{ dimension: initialValues.dimension }}
              onSearch={(params) => {
                handleSearch({ ...initialValues, ...params,current: 1 });// 强制重置为第一页
              }}
            />
          )}
          </div>
        }
        toolBarRender={() => [
          <div key="buttons" style={{ display: 'flex', alignItems: 'center', height: 40 }}>
            <Button onClick={exportCSV} type="primary">
              导出 Excel
            </Button>
          </div>,
        ]}      
        actionRef={actionRef}  // 绑定 actionRef
        options={{
          reload: false
          }}
        rowKey={(record, index) => index?.toString() ?? ''}
        columns={dynamicColumns}
        dataSource={dataSource}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total:  dataTotal,
          showSizeChanger: true,
          onChange: (page, pageSize) => {
            const isPageSizeChanged = pageSize !== pagination.pageSize;
            // 如果 pageSize 改变了，重置 current 为 1

            const newPage = isPageSizeChanged ? 1 : page;
            
            handleSearch({ ...initialValues, current: newPage, pageSize });
          },
        }}
        search={false}
        scroll={{
          x: true,
          y: '59vh'
        }}
      />
    </PageContainer>
  );
};

export default dispatch_detail;
